import 'dart:async';

import 'package:core_package/core_package.dart';
import 'package:core_package/share/my_font.dart';
import 'package:core_package/ui/widget/my_asset_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/core/withdraw_deposit_manager/withdraw_deposit_manager.dart';
import 'package:flutter_app_unionad/event_or_delegate/reload_event.dart';
import 'package:flutter_app_unionad/main/protocol_page.dart';
import 'package:flutter_app_unionad/model/share_pic_model.dart';
import 'package:flutter_app_unionad/model/take_save_model.dart';
import 'package:flutter_app_unionad/request/facility_request.dart';
import 'package:flutter_app_unionad/request/promotion_request.dart';
import 'package:flutter_app_unionad/ui/basice/base_navigation_height_widget.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/basice/title_alert_widget.dart';
import 'package:flutter_app_unionad/ui/my_facility/widget/select_pay_type_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/delegate/account_amount_delegate.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/assets_download_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/promotion_input_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/promotion_order_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/show_promotion_ad_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/task_center_widget.dart';
import 'package:flutter_app_unionad/ui/user_center/widget/binding_facility_widget.dart';
import 'package:flutter_app_unionad/ui/withdraw_deposit/withdraw_deposit_page.dart';
import 'package:flutter_app_unionad/view_model/change_device_event.dart';
import 'package:flutter_unionad/flutter_unionad.dart' as FlutterUnionad;

import 'widget/team_sell_widget.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';

class PromotionPage extends StatefulWidget {
  @override
  _PromotionPageState createState() => _PromotionPageState();
}

class _PromotionPageState extends State<PromotionPage>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin, AccountAmountDelegate, WidgetsBindingObserver {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  TabController? _controller;
  int index = 2;
  bool showBanner = true;
  bool showAd = false;

  TaskSaveModel model = TaskSaveModel(userPoint: 0, amount: 0, day: 0);

  PageController? _pageController;

  // List<String> titles = ["推广订单", "团队销售", "素材下载", "任务中心"];
  List<String> titles = ["推广订单", "素材下载", "任务中心"];

  Timer? _timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TabController(length: titles.length, vsync: this, initialIndex: index);
    _pageController = PageController(initialPage: index);
    PromotionRequest.getShareInfo(type: 3).then((value) {
      if (mounted)
        setState(() {
          item = value;
        });
    });
    eventBus.on<TabViewReloadDataEvent>().listen((event) {
      if (event.index == 1) {
        reloadAmount();
      }
    });
    reloadAmount();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      eventBus.fire(TaskDownTimerEvent());
    });
    int? time = UserCacheUil.getInt(Configuration.adTime);

    showAd = false;
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getAD();
    });
  }

  void getAD() async {
    final list = await PromotionRequest.getListByType(type: 2);
    print('list  $list');
    if (list != null && list.length != 0) {
      int? time = UserCacheUil.getInt(Configuration.adTime);
      String? idUrl = UserCacheUil.getString(Configuration.adUrl);

      if (time != null) {
        DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(time);
        if (DateTime.now().difference(dateTime).inDays < 30 && idUrl == list[0].coverImg) {
          return;
        }
      }
      showAd = true;
      setState(() {});
      ShowCenterAlertDialog.showAlert(
        context,
        builder: (context) {
          return ShowPromotionAdWidget(list[0]);
        },
        width: 320.px,
        height: 550.px,
        radius: 0,
        bgColor: Colors.transparent,
      ).then((value) {
        print('ddddd');
        setState(() {
          showAd = false;
        });
      });
    } else {
      setState(() {
        showAd = false;
      });
    }
  }

  Future<bool> bindingDevice() async {
    if (UserCacheUil.getString(Configuration.deviceId) == null ||
        UserCacheUil.getString(Configuration.deviceId)!.stringIsEmpty) {
      ProgressDialog.showProgress(context);
      final userDeviceListModel = await FacilityRequest.getUserDeviceListRequest();
      ProgressDialog.dismiss(context);
      if (userDeviceListModel != null &&
          userDeviceListModel.devList != null &&
          userDeviceListModel.devList!.length != 0) {
        if (UserCacheUil.getString(Configuration.deviceId) == null ||
            UserCacheUil.getString(Configuration.deviceId)!.stringIsEmpty) {
          for (var item in userDeviceListModel.devList!) {
            if (item.isDefault == 1) {
              UserCacheUil.setString(Configuration.deviceId, item.devId ?? '');
              break;
            }
          }
        }
        if (UserCacheUil.getString(Configuration.deviceId) == null ||
            UserCacheUil.getString(Configuration.deviceId)!.stringIsEmpty) {
          UserCacheUil.setString(Configuration.deviceId, userDeviceListModel.devList![0].devId ?? '');
        }
      }

      if (UserCacheUil.getString(Configuration.deviceId) == null ||
          UserCacheUil.getString(Configuration.deviceId)!.stringIsEmpty) {
        ShowCenterAlertDialog.showAlert(
          context,
          width: 300.px,
          height: 160.px,
          builder: (ctx) {
            return TitleAlertWidget(
              title: '提示',
              subTitle: '您还没有绑定设备',
              actions: ['取消', '绑定'],
              actionsTitleColors: [Colors.white, Colors.white],
              onTap: (int index) {
                if (index == 0) {
                  Navigator.pop(context);
                } else {
                  //
                  Navigator.pop(context, true);
                }
              },
              actionsColors: [MyColors.color_143_143_143, MyColors.color_245_174_41],
            );
          },
        ).then((value) {
          if (value != null && value) {
            ShowCenterAlertDialog.showAlert(context, builder: (ctx) {
              return BindingFacilityWidget();
            }, width: 335.px, height: 210.px);
          }
        });
        return false;
      }
    }
    return true;
  }

  //绑定设备
  void bindDevice() {}

  void withdrawDepositOnTap() {
    WithdrawDepositManager.withdrawDeposit(
      context,
      this,
      accountModel: model,
    );
  }

  void exchange() async {
    final future = await bindingDevice();
    if (!future) return;
    ShowCenterAlertDialog.showAlert(context, builder: (ctx) {
      return PromotionInputWidget(
        title: '请输入兑换天数',
        keyboardKey: TextInputType.numberWithOptions(decimal: false),
        isExchange: true,
        onTap: (value, devId) {
          //
          if (value.length == 0) {
            ShowToastWidget.showToast(msg: '请输入兑换天数');
            return;
          }
          if (double.parse(value) > model.day!) {
            ShowToastWidget.showToast(msg: '您当前的金币兑换天数最大不能超过${model.day}天');
            return;
          }
          if (double.parse(value) < 0) {
            ShowToastWidget.showToast(msg: '兑换天数不能小于1天');
            return;
          }
          FocusScope.of(context).requestFocus(FocusNode());

          ProgressDialog.showProgress(context);
          PromotionRequest.exchangePoint(amount: int.parse(value).toString(), devId: devId).then((value) {
            ProgressDialog.dismiss(context);

            if (value) {
              Navigator.pop(context);
              reloadAmount();
            }
          });
        },
      );
    }, width: 335.px, height: 240.px);
  }

  @override
  Widget build(BuildContext context) {
    return BaseNavigationHeightWidget(
      navHeight: 212.px + SizeFill.statusHeight!,
      needScrollView: false,
      child: Column(
        children: [
          buildBiNumberWidget(),
          MySizeBox(height: 15),
          buildButtonWidget(),
          MySizeBox(height: 27),
          buildTitleWidget(),
          MySizeBox(height: 10),
          buildContent(),
          MySizeBox(height: 10),
          (index != 2 || showAd)
              ? Container()
              : Column(
                  children: [
                    FlutterUnionad.FlutterUnionad.bannerAdView(
                      androidCodeId: "945133617",
                      //andrrid banner广告id 必填
                      iosCodeId: "939476891",
                      //ios banner广告id 必填
                      supportDeepLink: true,
                      //是否支持 DeepLink 选填
                      expressAdNum: 3,
                      //一次请求广告数量 大于1小于3 必填
                      expressTime: 5,
                      //轮播间隔事件 30-120秒  选填
                      expressViewWidth: SizeFill.screenWidth! - 20.px,
                      // 期望view 宽度 dp 必填
                      expressViewHeight: 95.px,
                      //期望view高度 dp 必填
                      downloadType: FlutterUnionad.FlutterUnionadDownLoadType.DOWNLOAD_TYPE_POPUP,

                      callBack: FlutterUnionad.FlutterUnionadBannerCallBack(onClick: () {
                        print('onClick');
                      }, onShow: () {
                        print('onShow');

                        setState(() {
                          showBanner = false;
                        });
                      }, onFail: (msg) {
                        print('onFail');
                        setState(() {
                          showBanner = false;
                        });
                      }, onDislike: (msg) {
                        print('onDislike');

                        setState(() {
                          showBanner = false;
                        });
                      }),
                      //     : (FlutterUnionad.FlutterUnionadState state) {
                      //   //广告事件回调 选填
                      //   //type onShow广告成功显示 onDislike不感兴趣 onFail广告加载失败
                      //   //params 详细说明
                      //   switch (state.type) {
                      //     case FlutterUnionad.onShow:
                      //       print(state.tojson());
                      //       setState(() {
                      //         showBanner = false;
                      //       });
                      //       break;
                      //     case FlutterUnionad.onFail:
                      //       print(state.tojson());
                      //       setState(() {
                      //         showBanner = false;
                      //       });
                      //       break;
                      //     case FlutterUnionad.onDislike:
                      //       print(state.tojson());
                      //       setState(() {
                      //         showBanner = false;
                      //       });
                      //       break;
                      //   }
                      // }
                    ),
                    !showAd || !showBanner ? Container() : SizedBox(height: 10.px),
                    buildBottomWidget(),
                    MySizeBox(height: 10),
                  ],
                ),
        ],
      ),
    );
  }

  Widget buildContent() {
    return Expanded(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(5.px),
        ),
        child: PageView(
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(),
          children: [
            TeamSellWidget(isTeam: false),
            // TeamSellWidget(isTeam: true),
            AssetsDownloadWidget(),
            TaskCenterWidget(delegate: this),
          ],
        ),
      ),
    );
  }

  Widget buildTitleWidget() {
    return Container(
      height: 90.px,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.px),
      ),
      child: TabTitleWidget(
          isScrollable: false,
          unSelectLabColor: MyColors.formHex("#272727FF"),
          labelColor: MyColors.formHex("#F8BA35FF"),
          labelStyle: TextStyle(fontSize: MyFont.font13, fontWeight: MyFontWeight.regular),
          unSelectLabStyle: TextStyle(fontSize: MyFont.font13, fontWeight: MyFontWeight.regular),
          tabController: _controller,
          indicatorBottom: 25.px,
          indicatorWidth: 36.px,
          padding: EdgeInsets.zero,
          labelPadding: EdgeInsets.zero,
          indicatorHeight: 1,
          indicatorColor: MyColors.formHex("#F8BA35FF"),
          titleWidgetList: List.generate(titles.length, (index) {
            return Row(
              children: [
                Expanded(child: Center(child: Text(titles[index]))),
                Visibility(
                  visible: index != titles.length - 1,
                  child: Container(
                    height: 30.px,
                    width: 1,
                    color: MyColors.color_238_238_238,
                  ),
                ),
              ],
            );
          }),
          onTop: (int index) {
            if (mounted) {
              this.index = index;
              setState(() {
                _pageController?.jumpToPage(index);
              });
            }
          }),
    );
  }

  Widget buildButtonWidget() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        MyButton(
          title: "提现",
          titleStyle: TextStyle(
            color: MyColors.color_27_27_27,
            fontSize: MyFont.font14,
            fontWeight: MyFontWeight.bold,
          ),
          onTap: () {
            withdrawDepositOnTap();
          },
          radius: 2.px,
          color: Colors.white,
          width: 133.px,
        ),
        MySizeBox(width: 15),
        MyButton(
          title: "兑现",
          titleStyle: TextStyle(
            color: MyColors.color_27_27_27,
            fontSize: MyFont.font14,
            fontWeight: MyFontWeight.bold,
          ),
          width: 133.px,
          onTap: () {
            //
            exchange();
          },
          radius: 2.px,
          color: Colors.white,
        )
      ],
    );
  }

  Widget buildBiNumberWidget() {
    return Stack(
      children: [
        Positioned(
          right: 10.px,
          top: 10.px,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              NavigatorUtil.push(context, ProtocolPage.routeName, arguments: 2);
            },
            child: Container(
              height: 20.px,
              width: 53.px,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                border: Border.all(color: MyColors.color_238_238_238, width: 1),
              ),
              alignment: Alignment.center,
              child: Text(
                "说明",
                style: TextStyle(
                  color: MyColors.color_27_27_27,
                  fontWeight: MyFontWeight.regular,
                  fontSize: MyFont.font10,
                ),
              ),
            ),
          ),
        ),
        Center(
          child: Column(
            children: [
              MySizeBox(height: 10),
              Text(
                "金币",
                style: TextStyle(
                  color: MyColors.color_27_27_27,
                  fontWeight: MyFontWeight.regular,
                  fontSize: MyFont.font13,
                ),
              ),
              MySizeBox(height: 5),
              Text(
                "${model.userPoint}",
                style: TextStyle(
                  color: MyColors.color_27_27_27,
                  fontWeight: MyFontWeight.bold,
                  fontSize: MyFont.font33,
                ),
              ),
            ],
          ),
        )
      ],
    );
  }

  Widget buildBottomWidget() {
    if (item == null) return Container();
    return Container(
      color: Colors.redAccent,
      width: 355.px,
      height: 57.px,
      child: Stack(
        children: [
          Positioned.fill(
            child: MyAssetImage(
              "icon_bg_4",
              fit: BoxFit.fill,
            ),
          ),
          Positioned(
            left: 0,
            top: 0,
            bottom: 0,
            width: 75.px,
            child: MyAssetImage(
              "icon_bg_4_left",
              fit: BoxFit.fill,
            ),
          ),
          Positioned(
            left: 0,
            top: 0,
            bottom: 0,
            width: 75.px,
            child: Container(
              alignment: Alignment.center,
              child: Text(
                "分享\n有礼",
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: MyFontWeight.bold,
                  fontSize: MyFont.font14,
                ),
              ),
            ),
          ),
          Positioned(
            left: 80.px,
            top: 0,
            bottom: 0,
            child: Container(
              alignment: Alignment.center,
              child: Text(
                "邀请好友安装\n可既得750,000金币",
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: MyFontWeight.regular,
                  fontSize: MyFont.font12,
                ),
              ),
            ),
          ),
          Positioned(
            right: 20.px,
            top: 13.5.px,
            child: GestureDetector(
              onTap: () {
                shareOnTap();
              },
              child: Container(
                width: 84.px,
                height: 30.px,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(MyAssetsImages.setAssetsImagesPath("icon_bg_5")),
                    fit: BoxFit.fill,
                  ),
                ),
                alignment: Alignment.center,
                child: Text(
                  "去分享",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: MyFontWeight.bold,
                    fontSize: MyFont.font12,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  SharePicModel? item;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller?.dispose();
    _pageController?.dispose();
    _timer?.cancel();
  }

  @override
  void reloadAmount() {
    print("reloadAmount");

    // TODO: implement reloadAmount
    PromotionRequest.getUserAccountAmount().then((value) {
      if (value != null && mounted)
        setState(() {
          model = value;
        });
    });
  }

  @override
  void reloadAmountWithOpen(point) {
    // TODO: implement reloadAmountWithOpen
    if (mounted)
      setState(() {
        this.model = point;
      });
  }

  void shareOnTap() {
    ShowBottomAlertDialog.showBottomDialog(
      context,
      builder: (ctx) {
        return SelectPayTypeWidget(
          title: '选择分享方式',
          icons: ['wx_1', 'wechat_moments'],
          weChatPayOnTop: () {
            //
            share(true);
          },
          alipayPayOnTop: () {
            //
            share(false);
          },
        );
      },
      height: 168.px + SizeFill.statusHeight!,
    );
  }

  void share(bool isSession) {
    SSDKMap ssdkMap = SSDKMap()
      ..setGeneral(
          //title	标题（String）
          item!.title!,
          // text	文本（String）
          '',
          //images	图片数组ios使用（dynamic）
          [MyAssetsImages.setAssetsImagesPath('icon_logo_1.png')],
          //imageUrlAndroid	url图片地址（String）
          "",
          "",
//          "${imageUrl}",
          //url	url地址（String）
          "${Configuration.h5Share}${FacilityRequest.encodeBase64(UserCacheUil.getString(Configuration.mobile) ?? '')}",
          //右侧图片地址
          MyAssetsImages.setAssetsImagesPath('icon_logo_1.png'),
          //musicUrlAndroid	音乐url地址（String）
          "",
          //videoUrlAndroid	视频url地址（String）
          "",
          //filePath	文件地址（String）
          "",
          //分享类型
          SSDKContentTypes.webpage);
    // ShowToastWidget.showToast(msg: '开始分享');
    try {
      SharesdkPlugin.share(isSession ? ShareSDKPlatforms.wechatSession : ShareSDKPlatforms.wechatTimeline, ssdkMap,
          (state, map1, map2, err) {
        // ShowToastWidget.showToast(msg: '${err.code} ---${err.userInfo}');
        //
        if (state == SSDKResponseState.Success) {}
      });
    } catch (e) {
      ShowToastWidget.showToast(msg: '$e');
    }
  }
}
